package com.adobe.apprise.commands
{
	import com.adobe.apprise.database.Database;
	import com.adobe.apprise.database.DatabaseResponder;
	import com.adobe.apprise.database.DatabaseEvent;
	import com.adobe.apprise.events.DeleteFeedEvent;
	import com.adobe.apprise.events.PopulateViewControlEvent;
	import com.adobe.apprise.model.ModelLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ArrayCollection;
	
	public class DeleteFeedCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var feedId:Number = DeleteFeedEvent(ce).feedId;
			deleteTopics(feedId);
		}
		
		private function deleteTopics(feedId:Number):void
		{
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					deleteAuthors(feedId);
				});
			ModelLocator.getInstance().db.deleteTopicsByFeedId(responder, feedId);
		}

		private function deleteAuthors(feedId:Number):void
		{
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					deletePosts(feedId);
				});
			ModelLocator.getInstance().db.deleteAuthorsByFeedId(responder, feedId);
		}

		private function deletePosts(feedId:Number):void
		{
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					deleteFeed(feedId);
				});
			ModelLocator.getInstance().db.deletePostsByFeedId(responder, feedId);
		}

		private function deleteFeed(feedId:Number):void
		{
			var responder:DatabaseResponder = new DatabaseResponder();
			responder.addEventListener(DatabaseEvent.RESULT_EVENT,
				function(e:DatabaseEvent):void
				{
					new PopulateViewControlEvent().dispatch();
					ModelLocator.getInstance().selectedPost = null;
					ModelLocator.getInstance().posts = new ArrayCollection();
				});
			ModelLocator.getInstance().db.deleteFeedById(responder, feedId);
		}
	}
}
